<?php

interface ApiPoolCrypter {
    public function encryptRequest($req);
    public function decryptRequest($req);
    public function encryptResponse($res);
    public function decryptResponse($res);
};

class ApiPoolCryptType {

	const NO_CRYPT = 0;
	const MD5_SIGN = 1;

};

abstract class ApiPoolBaseCrypter implements ApiPoolCrypter {
	
	protected $key = "";
	
	public function __construct($key) {
		$this->key = $key;
	}
}

class ApiPoolNullCrypter extends ApiPoolBaseCrypter {
	
	/**
	 * @param unknown_type $req
	 */
	public function encryptRequest($req) {
		return true;
	}

	/**
	 * @param unknown_type $req
	 */
	public function decryptRequest($req) {
		return true;
	}

	/**
	 * @param unknown_type $res
	 */
	public function encryptResponse($res) {
		return true;
	}

	/**
	 * @param unknown_type $res
	 */
	public function decryptResponse($res) {
		return true;
	}

}

class ApiPoolMD5SignCrypter extends ApiPoolBaseCrypter {
	
	const CRYPT_INTERVAL = 60;
	
	/**
	 * @param unknown_type $req
	 */
	public function encryptRequest($req) {
		$req->setCryptType(ApiPoolCryptType::MD5_SIGN);
		$marshal = $this->key;
		$marshal = $marshal.strval(floor(time()/(self::CRYPT_INTERVAL)));
		$marshal = $marshal.strval($req->getRequestSrc());
		$marshal = $marshal.strval($req->getServiceName()).".".strval($req->getApiName());
		$marshal = $marshal.strval(json_encode($req->getParamList()));
		$marshal = $marshal.strval($req->getId());
		$crypt_key = md5($marshal);
		$req->setCryptKey($crypt_key);
		return true;
	}

	/**
	 * @param unknown_type $req
	 */
	public function decryptRequest($req) {
		return true;
	}

	/**
	 * @param unknown_type $res
	 */
	public function encryptResponse($res) {
		return true;
	}

	/**
	 * @param unknown_type $res
	 */
	public function decryptResponse($res) {
		return true;
	}

}

class ApiPoolCryptFactory {
	static function newCrypter($type, $key) {
		switch ($type) {
		case ApiPoolCryptType::NO_CRYPT:
			return new ApiPoolNullCrypter($key);
		case ApiPoolCryptType::MD5_SIGN:
			return new ApiPoolMD5SignCrypter($key);
		default:
			return new ApiPoolNullCrypter($key);
		}
		return new ApiPoolNullCrypter($key);
	}
}

?>
